package com.op.teachingliteapp.common.api.smartpan;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Demo {

	public static void list() {
		String cmdJson = CmdForm.generateJsonCmd("123", "/课程", CmdForm.CMD_LIST);
		// Post参数加入"CMD",值为cmdJson
		System.out.println(cmdJson);

		// 发送POST请求给ApiConstant.SMART_PAN_URL
		// 获得Result
		String result = "";

		// result可以转成一个List
		List<EntityBean> entityBeanList = new ArrayList<EntityBean>();
		if (CmdForm.fillEntityBeanList(entityBeanList, result)) {
			System.out.println("获取到的Size为: " + entityBeanList.size());
		} else {
			System.out.println("路径有问题");
		}
	}

	public static void create() {
		String cmdJson = CmdForm.generateJsonCmd("123", "/Course", CmdForm.CMD_CREATE_FOLDER, "TestKK");
		// Post参数加入"CMD",值为cmdJson
		System.out.println(cmdJson);

		// 发送POST请求给ApiConstant.SMART_PAN_URL

		// 获得Result
		String result = "";

		// 打印出结果
		System.out.println(CmdForm.getOutputMessage(result));
	}

	public static void delete() {
		String cmdJson = CmdForm.generateJsonCmd("123", "/Course/Test", CmdForm.CMD_DELETE_FOLDER);
		// Post参数加入"CMD",值为cmdJson
		System.out.println(cmdJson);

		// 发送POST请求给ApiConstant.SMART_PAN_URL

		// 获得Result
		String result = "";

		// 打印出结果
		System.out.println(CmdForm.getOutputMessage(result));
	}

	public static void upload() {
		String ownerId = "";
		String path = "";
		String fileName = "";

		String cmdJson = CmdForm.generateJsonCmd(ownerId, path, CmdForm.CMD_UPLOAD, fileName);
	}

	public static void updata() {
		String ownerId = "";
		String path = "";
		String fileName = "";

		// path后如果没有"/",记得加"/"
		String cmdJson = CmdForm.generateJsonCmd(ownerId, path + fileName, CmdForm.CMD_UPDATA);
	}

	public static void download() {
		String ownerId = "";
		String path = "";
		String fileName = "";

		// path后如果没有"/",记得加"/"
		String cmdJson = CmdForm.generateJsonCmd(ownerId, path + fileName, CmdForm.CMD_DOWNLOAD);

		String output = "";
		
		saveByteArrayToFile(fileName, output.getBytes());
		
	}
	
	public static boolean saveByteArrayToFile(String fileName, byte[] data) {
		boolean success = false;
		if (null != fileName) {
			String name = fileName;
			int count = 0;
			File file = new File(name);
			while (file.exists()) {
				count++;
				name = fileName + count;
				file = new File(name);
			}
			file.getParentFile().mkdirs();
			try {
				FileOutputStream fs = new FileOutputStream(fileName);
				fs.write(data);
				fs.close();
				success = true;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return success;
		} else {
			return success;
		}
	}

}
